/**
 * 随机事件系统
 */
const EventSystem = {
    /**
     * 处理随机事件
     */
    processRandomEvents() {
        // 每年有一定概率触发随机事件
        if (Utils.chance(CONFIG.EVENTS.CHANCE_PER_YEAR)) {
            // 随机选择一个王国
            const kingdom = Utils.randomSample(GameData.kingdoms, 1)[0];
            
            // 确定事件类型
            let eventType;
            const random = Math.random();
            
            if (random < CONFIG.EVENTS.TYPES.POSITIVE) {
                eventType = 'positive';
            } else if (random < CONFIG.EVENTS.TYPES.POSITIVE + CONFIG.EVENTS.TYPES.NEUTRAL) {
                eventType = 'neutral';
            } else {
                eventType = 'negative';
            }
            
            // 触发对应类型的事件
            switch (eventType) {
                case 'positive':
                    this.triggerPositiveEvent(kingdom);
                    break;
                case 'neutral':
                    this.triggerNeutralEvent(kingdom);
                    break;
                case 'negative':
                    this.triggerNegativeEvent(kingdom);
                    break;
            }
        }
        
        // 处理魔王倒计时
        this.processBossCountdown();
    },
    
    /**
     * 触发正面事件
     * @param {Object} kingdom - 目标王国
     */
    triggerPositiveEvent(kingdom) {
        const events = [
            {
                name: "金矿发现",
                effect: () => {
                    const resourceGain = Utils.randomInt(150, 250);
                    kingdom.resources += resourceGain;
                    Utils.addLogEntry(`${kingdom.name}发现了金矿，资源+${resourceGain}`, 'positive');
                }
            },
            {
                name: "丰收年",
                effect: () => {
                    const populationGain = Math.floor(kingdom.population * 0.1);
                    kingdom.population += populationGain;
                    Utils.addLogEntry(`${kingdom.name}迎来丰收年，人口+${Utils.formatNumber(populationGain)}`, 'positive');
                }
            },
            {
                name: "军事改革",
                effect: () => {
                    const militaryGain = Math.floor(kingdom.military * 0.15);
                    kingdom.military += militaryGain;
                    Utils.addLogEntry(`${kingdom.name}完成军事改革，军事力量+${Utils.formatNumber(militaryGain)}`, 'positive');
                }
            },
            {
                name: "技术突破",
                effect: () => {
                    const resourceGain = Math.floor(kingdom.resources * 0.2);
                    const militaryGain = Math.floor(kingdom.military * 0.1);
                    kingdom.resources += resourceGain;
                    kingdom.military += militaryGain;
                    Utils.addLogEntry(`${kingdom.name}取得技术突破，资源+${Utils.formatNumber(resourceGain)}，军事力量+${Utils.formatNumber(militaryGain)}`, 'positive');
                }
            },
            {
                name: "英雄崛起",
                effect: () => {
                    // 生成一个高能力值的NPC
                    const race = GameData.getRaceById(kingdom.raceId);
                    const ability = Utils.randomInt(180, 250);
                    const npc = {
                        id: Utils.generateId(),
                        raceId: kingdom.raceId,
                        name: Utils.generateRandomName('npc', kingdom.raceId),
                        ability: ability,
                        birthYear: GameData.gameState.currentYear - Utils.randomInt(18, 30),
                        status: "存活",
                        deathYear: null
                    };
                    
                    GameData.npcs.push(npc);
                    Utils.addLogEntry(`${kingdom.name}出现了一位天赋异禀的英雄：${npc.name}，能力值${npc.ability}`, 'positive');
                }
            }
        ];
        
        // 随机选择一个事件并执行
        const event = Utils.randomSample(events, 1)[0];
        event.effect();
    },
    
    /**
     * 触发中性事件
     * @param {Object} kingdom - 目标王国
     */
    triggerNeutralEvent(kingdom) {
        const events = [
            {
                name: "商队来访",
                effect: () => {
                    const resourceChange = Math.floor(kingdom.resources * 0.05);
                    const populationChange = Math.floor(kingdom.population * 0.02);
                    kingdom.resources -= resourceChange;
                    kingdom.population += populationChange;
                    Utils.addLogEntry(`商队来访${kingdom.name}，资源-${Utils.formatNumber(resourceChange)}，人口+${Utils.formatNumber(populationChange)}`, 'normal');
                }
            },
            {
                name: "文化交流",
                effect: () => {
                    // 随机选择另一个王国
                    const otherKingdoms = GameData.kingdoms.filter(k => k.id !== kingdom.id);
                    if (otherKingdoms.length > 0) {
                        const otherKingdom = Utils.randomSample(otherKingdoms, 1)[0];
                        const resourceExchange = Math.floor(kingdom.resources * 0.03);
                        kingdom.resources -= resourceExchange;
                        otherKingdom.resources += resourceExchange;
                        Utils.addLogEntry(`${kingdom.name}与${otherKingdom.name}进行文化交流，资源转移${Utils.formatNumber(resourceExchange)}`, 'normal');
                    }
                }
            },
            {
                name: "迁徙活动",
                effect: () => {
                    // 随机选择另一个王国
                    const otherKingdoms = GameData.kingdoms.filter(k => k.id !== kingdom.id);
                    if (otherKingdoms.length > 0) {
                        const otherKingdom = Utils.randomSample(otherKingdoms, 1)[0];
                        const populationMove = Math.floor(kingdom.population * 0.05);
                        kingdom.population -= populationMove;
                        otherKingdom.population += populationMove;
                        Utils.addLogEntry(`${Utils.formatNumber(populationMove)}人口从${kingdom.name}迁徙到${otherKingdom.name}`, 'normal');
                    }
                }
            },
            {
                name: "边境调整",
                effect: () => {
                    // 模拟边境调整，资源和军事力量小幅变化
                    const resourceChange = Math.floor(kingdom.resources * (Math.random() * 0.1 - 0.05));
                    const militaryChange = Math.floor(kingdom.military * (Math.random() * 0.1 - 0.05));
                    kingdom.resources += resourceChange;
                    kingdom.military += militaryChange;
                    
                    const resourceMsg = resourceChange >= 0 ? `资源+${Utils.formatNumber(resourceChange)}` : `资源${Utils.formatNumber(resourceChange)}`;
                    const militaryMsg = militaryChange >= 0 ? `军事力量+${Utils.formatNumber(militaryChange)}` : `军事力量${Utils.formatNumber(militaryChange)}`;
                    
                    Utils.addLogEntry(`${kingdom.name}进行边境调整，${resourceMsg}，${militaryMsg}`, 'normal');
                }
            }
        ];
        
        // 随机选择一个事件并执行
        const event = Utils.randomSample(events, 1)[0];
        event.effect();
    },
    
    /**
     * 触发负面事件
     * @param {Object} kingdom - 目标王国
     */
    triggerNegativeEvent(kingdom) {
        const events = [
            {
                name: "瘟疫爆发",
                effect: () => {
                    const populationLoss = Math.floor(kingdom.population * 0.15);
                    kingdom.population -= populationLoss;
                    
                    // 添加持续效果（3年）
                    this.addPlagueEffect(kingdom, 3);
                    
                    Utils.addLogEntry(`${kingdom.name}爆发瘟疫，人口-${Utils.formatNumber(populationLoss)}，将持续3年`, 'important');
                }
            },
            {
                name: "自然灾害",
                effect: () => {
                    const populationLoss = Math.floor(kingdom.population * 0.08);
                    const resourceLoss = Math.floor(kingdom.resources * 0.2);
                    kingdom.population -= populationLoss;
                    kingdom.resources -= resourceLoss;
                    Utils.addLogEntry(`${kingdom.name}遭遇自然灾害，人口-${Utils.formatNumber(populationLoss)}，资源-${Utils.formatNumber(resourceLoss)}`, 'important');
                }
            },
            {
                name: "种族冲突",
                effect: () => {
                    // 随机选择另一个王国
                    const otherKingdoms = GameData.kingdoms.filter(k => k.id !== kingdom.id);
                    if (otherKingdoms.length > 0) {
                        const otherKingdom = Utils.randomSample(otherKingdoms, 1)[0];
                        
                        // 双方损失
                        const populationLoss1 = Math.floor(kingdom.population * 0.1);
                        const populationLoss2 = Math.floor(otherKingdom.population * 0.1);
                        const militaryLoss1 = Math.floor(kingdom.military * 0.1);
                        const militaryLoss2 = Math.floor(otherKingdom.military * 0.1);
                        
                        kingdom.population -= populationLoss1;
                        kingdom.military -= militaryLoss1;
                        otherKingdom.population -= populationLoss2;
                        otherKingdom.military -= militaryLoss2;
                        
                        Utils.addLogEntry(`${kingdom.name}与${otherKingdom.name}发生种族冲突，双方各损失约10%人口和军事力量`, 'important');
                    }
                }
            },
            {
                name: "内乱",
                effect: () => {
                    const populationLoss = Math.floor(kingdom.population * 0.05);
                    const militaryLoss = Math.floor(kingdom.military * 0.15);
                    const resourceLoss = Math.floor(kingdom.resources * 0.1);
                    
                    kingdom.population -= populationLoss;
                    kingdom.military -= militaryLoss;
                    kingdom.resources -= resourceLoss;
                    
                    Utils.addLogEntry(`${kingdom.name}爆发内乱，人口-${Utils.formatNumber(populationLoss)}，军事力量-${Utils.formatNumber(militaryLoss)}，资源-${Utils.formatNumber(resourceLoss)}`, 'important');
                }
            },
            {
                name: "资源枯竭",
                effect: () => {
                    const resourceLoss = Math.floor(kingdom.resources * 0.3);
                    kingdom.resources -= resourceLoss;
                    Utils.addLogEntry(`${kingdom.name}主要资源点枯竭，资源-${Utils.formatNumber(resourceLoss)}`, 'important');
                }
            }
        ];
        
        // 随机选择一个事件并执行
        const event = Utils.randomSample(events, 1)[0];
        event.effect();
    },
    
    /**
     * 添加瘟疫持续效果
     * @param {Object} kingdom - 目标王国
     * @param {number} duration - 持续年数
     */
    addPlagueEffect(kingdom, duration) {
        if (!kingdom.effects) {
            kingdom.effects = [];
        }
        
        kingdom.effects.push({
            type: 'plague',
            duration: duration,
            effect: (k) => {
                const populationLoss = Math.floor(k.population * 0.05);
                k.population -= populationLoss;
                Utils.addLogEntry(`${k.name}瘟疫持续，人口-${Utils.formatNumber(populationLoss)}`, 'important');
            }
        });
    },
    
    /**
     * 处理持续效果
     */
    processEffects() {
        GameData.kingdoms.forEach(kingdom => {
            if (kingdom.effects && kingdom.effects.length > 0) {
                // 应用所有持续效果
                kingdom.effects.forEach(effect => {
                    effect.effect(kingdom);
                    effect.duration--;
                });
                
                // 移除已结束的效果
                kingdom.effects = kingdom.effects.filter(effect => effect.duration > 0);
            }
        });
    },
    
    /**
     * 处理魔王倒计时
     */
    processBossCountdown() {
        // 减少倒计时
        GameData.gameState.bossCountdown--;
        
        // 如果倒计时小于等于0，触发魔王挑战
        if (GameData.gameState.bossCountdown <= 0) {
            this.triggerBossChallenge();
        }
        // 如果倒计时小于等于警告年限，显示警告
        else if (GameData.gameState.bossCountdown <= CONFIG.BOSS.WARNING_YEARS) {
            Utils.addLogEntry(`警告：魔王将在${GameData.gameState.bossCountdown}年后降临！`, 'important');
            
            // 更新UI显示
            const bossCountdownElement = document.getElementById('boss-countdown');
            if (bossCountdownElement) {
                bossCountdownElement.classList.add('warning');
            }
        }
    },
    
    /**
     * 触发魔王挑战
     */
    triggerBossChallenge() {
        // 计算魔王能力值
        const totalMilitary = GameData.kingdoms.reduce((sum, kingdom) => sum + kingdom.military, 0);
        GameData.boss.ability = Math.floor(totalMilitary * CONFIG.BOSS.POWER_MULTIPLIER + GameData.gameState.currentPlane * CONFIG.BOSS.PLANE_DIFFICULTY);
        
        // 生成魔王弱点
        const raceIds = GameData.races.map(race => race.id);
        const weaknessRaceId = Utils.randomSample(raceIds, 1)[0];
        const weaknessEffect = -0.2 - Math.random() * 0.1; // -20%到-30%之间
        
        GameData.boss.weakness = {
            raceId: weaknessRaceId,
            effect: weaknessEffect
        };
        
        // 显示魔王挑战界面
        UI.showBossChallenge();
        
        // 暂停游戏
        Game.setSpeed(CONFIG.GAME_SPEED.PAUSED);
        
        Utils.addLogEntry(`魔王"${GameData.boss.name}"降临大陆！`, 'important');
    },
    
    /**
     * 计算玩家总战力
     * @returns {number} 玩家总战力
     */
    calculatePlayerPower() {
        // 所有王国军事值总和
        const totalMilitary = GameData.kingdoms.reduce((sum, kingdom) => sum + kingdom.military, 0);
        
        // 强者榜TOP10能力值总和
        const top10Power = GameData.strongestList.slice(0, 10).reduce((sum, item) => sum + item.npc.ability, 0);
        
        return Math.floor(totalMilitary + top10Power * 5);
    },
    
    /**
     * 执行魔王挑战
     * @returns {boolean} 是否胜利
     */
    executeBossChallenge() {
        const playerPower = this.calculatePlayerPower();
        
        // 应用魔王弱点
        let bossAbility = GameData.boss.ability;
        
        // 检查是否有王国种族与魔王弱点匹配
        const weaknessRace = GameData.races.find(race => race.id === GameData.boss.weakness.raceId);
        if (weaknessRace) {
            const weaknessKingdom = GameData.kingdoms.find(kingdom => kingdom.raceId === weaknessRace.id);
            if (weaknessKingdom) {
                // 应用弱点效果
                bossAbility = Math.floor(bossAbility * (1 + GameData.boss.weakness.effect));
                Utils.addLogEntry(`魔王对${weaknessRace.name}有弱点，能力值降低至${Utils.formatNumber(bossAbility)}`, 'positive');
            }
        }
        
        // 判定胜负
        const victory = playerPower > bossAbility;
        
        if (victory) {
            Utils.addLogEntry(`大陆联军成功击败了魔王"${GameData.boss.name}"！`, 'positive');
            
            // 解锁下一位面
            GameData.gameState.currentPlane++;
            GameData.gameState.bossCountdown = CONFIG.BOSS.FIRST_ATTACK;
            
            // 生成新的魔王
            GameData.generateBoss();
            
            Utils.addLogEntry(`解锁新位面：第${GameData.gameState.currentPlane}位面`, 'positive');
        } else {
            Utils.addLogEntry(`大陆联军不敌魔王"${GameData.boss.name}"，遭受重创！`, 'important');
            
            // 增加失败计数
            GameData.bossFailures++;
            
            // 检查是否达到5次失败
            if (GameData.bossFailures >= 5) {
                // 全大陆毁灭
                GameData.kingdoms.forEach(kingdom => {
                    kingdom.population = 0;
                    kingdom.resources = 0;
                    kingdom.military = 0;
                });
                
                Utils.addLogEntry(`魔王"${GameData.boss.name}"彻底毁灭了大陆！所有王国被夷为平地！`, 'important');
                GameData.bossFailures = 0; // 重置失败计数
                GameData.gameState.currentYear = 0; // 重置当前年份
                GameData.gameState.bossCountdown = 100; // 重置魔王袭击时间为100年
                GameData.kingdoms.forEach(kingdom => {
                    kingdom.population = 5; // 重置人口为5
                    kingdom.resources = 100; // 重置资源为100
                });
            } else {
                // 所有王国损失一定比例的人口和军事力量
                GameData.kingdoms.forEach(kingdom => {
                    const populationLoss = Math.floor(kingdom.population * 0.2);
                    const militaryLoss = Math.floor(kingdom.military * 0.3);
                    
                    kingdom.population -= populationLoss;
                    kingdom.military -= militaryLoss;
                });
                
                // 10%概率生成天选之子
                if (Math.random() < 0.1) {
                    const chosenOne = NPCSystem.generateNPC({
                        ability: 800, // 调整能力值
                        name: "天选之子"
                    });
                    
                    // 随机加入一个王国
                    const randomKingdom = GameData.kingdoms[Math.floor(Math.random() * GameData.kingdoms.length)];
                    randomKingdom.npcs.push(chosenOne);
                    
                    Utils.addLogEntry(`在绝望中，一位天选之子"${chosenOne.name}"诞生了！他将极大增强王国战力！`, 'positive');
                }
                
                // 重置魔王倒计时（给玩家第二次机会）
                GameData.gameState.bossCountdown = 20;
                
                Utils.addLogEntry(`魔王将在${GameData.gameState.bossCountdown}年后再次降临！`, 'important');
            }
        }
        
        return victory;
    }
};